package com.hll.fliter;

import com.hll.utils.Constant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: JavaWebDemo-01
 * @description:
 * @author: Mr.Hu
 * @create: 2021-03-06 20:53
 */
public class LoginFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {}

  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    // 对sys/success.jsp监听
    HttpServletRequest request = (HttpServletRequest) servletRequest; // 转为标准request好写些
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    // 如果未登录,跳转至login
    Object attribute = request.getSession().getAttribute(Constant.LOGIN_ATTRIBUTE);
    if (attribute == null) {
      response.sendRedirect(request.getContextPath() + "/login.jsp");
    }

    filterChain.doFilter(request, response); // 差点忘了这一句
  }

  @Override
  public void destroy() {}
}
